package show.me.the.money.accredit;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import show.me.the.money.config.ConfigController;
import show.me.the.money.config.MultiConfigController;


public class RolesController extends MultiConfigController{
	private static Log logger = LogFactory.getLog(RolesController.class);
	private static RolesController rc;
	public static final String R_SIGN = "-";
	
	private RolesController(){	
		CATALOG = ConfigController.CATA_ROLE;   //"roles"
	}
	
	public static RolesController instance(){
		if(rc == null){
			rc = new RolesController();
		}
		return rc;
	}
	
	public boolean hasRole(String id){
		if(defineDoc == null || id == null){
			return false;
		}
		Element define = defineDoc.getRootElement();
		Node n = define.selectSingleNode("role[@id='" + id + "']");	
		return n != null ;
	}
	
	public Role getRole(String id){    // A-system
		if(defineDoc == null || id == null){
			return null;
		}
		String rid = id;
		int p = id.indexOf(R_SIGN);
		if(p>-1){
			rid = id.substring(p+1);
		}
		Role role = (Role)cache.get(id);
		if(role == null){
			Document doc = getConfigDoc(rid);
			if(doc != null){
				role = new Role(rid);
				role.setDefineDoc(doc);
				cache.put(id, role);
			}
			else{
				logger.fatal("role id[" + rid + "] not found.");
			}
		}
		return role;
	}
		
	@SuppressWarnings("unchecked")
	public List<Role> getChildRoles(String id){
		if(defineDoc == null || id == null){
			return null;
		}
		Element define = defineDoc.getRootElement();
		List<Role> roles =  new ArrayList<Role>();
		List<Element> ls = define.selectNodes("role[@parent='" + id + "']");
		for(Element el:ls){
			String sid = el.attributeValue("id");
			roles.add(getRole(sid));
		}
		return roles;
	}
	
	public void removeDoc(String id){
		if(cfgServer != null && cfgServer.isDocExist(CATALOG, id)){
			cfgServer.removeDoc(CATALOG, id);
		}
	}
	
	public void reload(String id){
		for(Iterator<String> it = cache.keySet().iterator();it.hasNext();){
			String key = it.next();
			if(key.contains(id)){				
				it.remove();
			}
		}
		if(vers.containsKey(id)){
			vers.remove(id);
		}		
		logger.info("{action:'Reload',catalog:'" + CATALOG + "',docId:'" + id + "'}");
	}
	
	public void clear(String id){
		reload(id);
		if(cfgServer != null){
			uploadServerDoc(id);
		}
	}
	
}
